package com.ld.common.webnotice.socket;

import com.corundumstudio.socketio.SocketConfig;
import com.corundumstudio.socketio.SocketIOServer;
import com.ld.common.webnotice.model.SocketIOParams;
import com.ld.shieldsb.common.core.model.PropertiesModel;

public class SocketIOServerInstance {

    /**
     * 初始化server
     * 
     * @return
     */
    public static SocketIOServer getSocketIOServer() {
        String host = PropertiesModel.CONFIG.getString(SocketIOParams.PARAM_SERVER_HOST, "localhost");
        Integer port = PropertiesModel.CONFIG.getInt(SocketIOParams.PARAM_SERVER_PORT, 9092);
        // socket连接数大小（如只监听一个端口boss线程组为1即可）
        int bossCount = PropertiesModel.CONFIG.getInt("socketio.bossCount", 1);
        int workCount = PropertiesModel.CONFIG.getInt("socketio.workCount", 100);
        boolean allowCustomRequests = PropertiesModel.CONFIG.getBoolean("socketio.allowCustomRequests", true);

        // 协议升级超时时间（毫秒），默认10秒。HTTP握手升级为ws协议超时时间
        int upgradeTimeout = PropertiesModel.CONFIG.getInt("socketio.upgradeTimeout", 1000000);

        // # Ping消息超时时间（毫秒），默认60秒，这个时间间隔内没有接收到心跳消息就会发送超时事件
        int pingTimeout = PropertiesModel.CONFIG.getInt("socketio.pingTimeout", 6000000);

        // Ping消息间隔（毫秒），默认25秒。客户端向服务器发送一条心跳消息间隔
        int pingInterval = PropertiesModel.CONFIG.getInt("socketio.pingInterval", 25000);

        Boolean inited = PropertiesModel.CONFIG.getBoolean(SocketIOParams.PARAM_INITED, false);
        if (!inited) {
            PropertiesModel.CONFIG.save(SocketIOParams.PARAM_SERVER_HOST, host, "_socketio服务host");
            PropertiesModel.CONFIG.save(SocketIOParams.PARAM_SERVER_PORT, port + "", "_socketio服务端口");
            PropertiesModel.CONFIG.save(SocketIOParams.PARAM_INITED, "true", "_是否已经初始化");
        }
        SocketConfig socketConfig = new SocketConfig();
        socketConfig.setTcpNoDelay(true);
        socketConfig.setReuseAddress(true);// 解决SOCKET服务端重启"Address already in use"异常
//        socketConfig.setSoLinger(0); // ie下不兼容
        com.corundumstudio.socketio.Configuration config = new com.corundumstudio.socketio.Configuration();
        config.setSocketConfig(socketConfig);
        config.setOrigin(null); // 注意如果开放跨域设置，需要设置为null而不是"*"
        config.setHostname(host);
        config.setPort(port);
        config.setBossThreads(bossCount);
        config.setWorkerThreads(workCount);
        config.setAllowCustomRequests(allowCustomRequests);
        config.setUpgradeTimeout(upgradeTimeout);
        config.setPingTimeout(pingTimeout);
        config.setPingInterval(pingInterval);

        return new SocketIOServer(config);
    }
}
